package com.gongpingjialoan.activity.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.bean.Monitor;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.utility.DhUtil;
import com.gongpingjialoan.utility.StepMonitor;
import com.gongpingjialoan.view.RLScrollView;
import com.gongpingjialoan.widget.LoadingDialog;
import com.gongpingjialoan.widget.MySwipeBackActivity;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.umeng.analytics.MobclickAgent;

import me.imid.swipebacklayout.lib.SwipeBackLayout;

public class BaseActivity extends MySwipeBackActivity {

    // private ActivityTack tack = ActivityTack.getInstanse();
    Activity ac;

    public BaseActivity mySelf = this;

    private LoadingDialog loadingPb;

    public String from = "";

    public String action = "";  //动作id

    public String type_action = "enter";  //动作类型

    public float roll_pages = 1.0f;  //滑屏

    public boolean isSendData = false;

    public boolean isScrollPage = false;

    private boolean isFrist = true;

    private RLScrollView scrollView;

    private PullToRefreshListView mPullToRefreshListView;

    private ListView mListView;

    public int scrollHeight = 0;


    private SwipeBackLayout mSwipeBackLayout;

    public Handler mHandler = new Handler();
    protected View backV;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSwipeBackLayout = getSwipeBackLayout();
        mSwipeBackLayout.setEdgeTrackingEnabled(SwipeBackLayout.EDGE_LEFT);
//        mSwipeBackLayout.setShadow(R.drawable.trans, SwipeBackLayout.EDGE_LEFT);
//        mSwipeBackLayout.setScrimColor(Color.TRANSPARENT);
//        mSwipeBackLayout.setEdgeSize(this.getResources().getDisplayMetrics().widthPixels / 2);
    }

    public void setSwipeEnagle(){
        if(mSwipeBackLayout!=null){
            mSwipeBackLayout.setEnableGesture(false);
        }
    }



    public void showProgressDialog(String msg) {
        if (!isFinishing()) {
            if (loadingPb == null) {
                loadingPb = new LoadingDialog(this);
            }
            loadingPb.setText(msg);
            loadingPb.show();
        }
    }


    public void showProgressDialog() {
        if (!isFinishing()) {
            if (loadingPb == null) {
                loadingPb = new LoadingDialog(this);
            }
            loadingPb.show();
        }
    }

    public void hidenProgressDialog() {
        if (!isFinishing()) {
            if (loadingPb != null) {
                loadingPb.dismiss();
            }
        }
    }


    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initTitleBar();
    }

    public void initBase(Activity acitvity) {
        this.ac = acitvity;
        // loadingPb = (ProgressBar)mySelf.findViewById(R.id.loading_pb);
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public void finish() {
        super.finish();
        // tack.removeActivity(this);
    }

    private void goMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    public void initTitleBar() {
        backV = findViewById(R.id.title_back);
        if (backV != null) {
            backV.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    finish();
                }
            });
        }
    }


    public void setTitle(String title) {
        TextView titleT = (TextView) findViewById(R.id.top_title);
        if (titleT != null) {
            titleT.setText(title);
        }
    }

    public void setTitle(String title, int type) {
        TextView titleT = (TextView) findViewById(R.id.top_title);
        if (titleT != null) {
            titleT.setText(title);
            titleT.setTextSize(16f);
        }
    }

    public void setRightTitle(String title) {
        TextView titleT = (TextView) findViewById(R.id.right_title);
        if (titleT != null) {
            titleT.setVisibility(View.VISIBLE);
            titleT.setText(title);
        }
    }
    public void setRightImage(int rid,View.OnClickListener click) {
        ImageView imgI = (ImageView) findViewById(R.id.right_img);
        if (imgI != null) {
            imgI.setVisibility(View.VISIBLE);
            imgI.setImageResource(rid);
            if(click != null){
                imgI.setOnClickListener(click);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isSendData) {
            StepMonitor.getInstance().addMonitor(new Monitor(type_action, action, System.currentTimeMillis(), roll_pages));
            if (isFrist && isScrollPage) {
                isFrist = !isFrist;
                try {
                    scrollView = (RLScrollView) findViewById(R.id.scrollview);
                    mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.listview);
                    mListView = (ListView) findViewById(R.id.list_view);
                } catch (Exception e) {
                }
                if (scrollView != null) {
                    registerScrollView();
                }
                if (mListView != null) {
                    registerListView();
                }
                if (mPullToRefreshListView != null) {
                    registerPullToRefreshListView();
                }
            }
        }
        MobclickAgent.onResume(this);
    }

    private void registerScrollView() {
        scrollView.setOnScrollListener(new RLScrollView.OnScrollListener() {
            @Override
            public void onScrollChanged(int x, int y, int oldX, int oldY) {
            }

            @Override
            public void onScrollStopped() {
                int height = scrollView.getScrollY();
                //记录最高的滑动距离
                if (height >= scrollHeight) {
                    scrollHeight = height;
                    roll_pages = DhUtil.getRollPages(GPJApplication.getInstance(), scrollHeight);
                }
            }

            @Override
            public void onScrolling() {
            }
        });

    }

    private void registerPullToRefreshListView() {
        mPullToRefreshListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    int height = getPullToRefreshListViewScrollY();
                    //记录最高的滑动距离
                    if (height >= scrollHeight) {
                        scrollHeight = height;
                        roll_pages = DhUtil.getRollPages(GPJApplication.getInstance(), scrollHeight);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

    }

    public int getPullToRefreshListViewScrollY() {
        View c = mPullToRefreshListView.getRefreshableView().getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = mPullToRefreshListView.getRefreshableView().getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }


    private void registerListView() {
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    int height = getListViewScrollY();
                    //记录最高的滑动距离
                    if (height >= scrollHeight) {
                        scrollHeight = height;
                        roll_pages = DhUtil.getRollPages(GPJApplication.getInstance(), scrollHeight);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

    }

    public int getListViewScrollY() {
        View c = mListView.getChildAt(0);
        if (c == null) {
            return 0;
        }
        int firstVisiblePosition = mListView.getFirstVisiblePosition();
        int top = c.getTop();
        return -top + firstVisiblePosition * c.getHeight();
    }


    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        if (isScrollPage && !TextUtils.isEmpty(action)) {
            StepMonitor.getInstance().addMonitor(new Monitor("scroll", action, System.currentTimeMillis(), roll_pages));
        }
    }

    /**
     * Toast 提示消息
     *
     * @param type 1：成功提示（用在请求成功后） 2：警告提示 3：成功提示（用在操作成功后） 4：失败提示
     * @param msg  提示消息
     */
    public void showTips(int type, String msg) {
        Toast.makeText(mySelf, msg, Toast.LENGTH_SHORT).show();
    }

}
